import { computed, type ComputedRef, ref, unref, watch } from 'vue';
import type { BasicTableProps } from '../types/table';
import type { PaginationProps } from 'element-plus';
import { isBoolean } from 'lodash-es';
import { PAGE_SIZE, PAGE_SIZE_OPTIONS, PAGINATION_LAYOUT } from '../const';
import type { PaginationPropsType } from '../types/pagination';

export function useVxePagination(refProps: ComputedRef<BasicTableProps>) {
  const configRef = ref<PaginationPropsType | PaginationProps>();
  const show = ref(true);
  // 监听pagination
  watch(
    () => unref(refProps).pagination,
    (pagination) => {
      if (!isBoolean(pagination) && pagination) {
        configRef.value = {
          ...unref(configRef),
          ...(pagination ?? {}),
        };
      }
    },
  );
  //   分页数据
  const getPaginationInfo = computed((): PaginationPropsType | PaginationProps | boolean => {
    const { pagination } = unref(refProps);
    if (!unref(show) || (isBoolean(pagination) && !pagination)) {
      return false;
    }
    // console.log("分页数据", pagination)

    return {
      currentPage: 1,
      pageSize: PAGE_SIZE,
      defaultPageSize: PAGE_SIZE,
      pageSizes: PAGE_SIZE_OPTIONS,
      showTotal: true,
      layout: PAGINATION_LAYOUT,
      ...unref(configRef),
    };
  });

  function setPagination(info: Partial<PaginationProps | PaginationPropsType>) {
    const paginationInfo = unref(getPaginationInfo);
    // console.log("setPagination", info)

    configRef.value = {
      ...(!isBoolean(paginationInfo) ? paginationInfo : {}),
      ...info,
    };
  }

  function getShowPagination() {
    return unref(show);
  }

  async function setShowPagination(flag: boolean) {
    show.value = flag;
  }

  return { getPaginationInfo, setShowPagination, getShowPagination, setPagination };
}
